<template>
  <div>
    <h3 class="scoreStateTitle">作业总览</h3>
    <div class="score-distribution">
      <!-- 分数段分布部分 -->
      <div class="distribution-section anchor-offset" id="fractional-distribution">
        <h3 class="header-with-select">分数段分布图表/表格</h3>
        <div class="segment-control">
          <span class="label">分数段默认为：</span>
          <div class="buttoncontent">
            <el-input v-model="segment"></el-input> <i>分/段</i>
          </div>
          <div>，分数段默认上限为最高分，下限为最低分。</div>
          <el-button type="primary" size="small" @click="handleSegmentChange">
            确定
          </el-button>
        </div>

        <!-- 图表展示 -->
        <div class="chart-container" v-if="tableData.length > 0">
          <div ref="chartRef" style="width: 100%; height: 400px"></div>
        </div>
        <div v-else style="line-height: 60px;width:100%;color: #909399;text-align: center;font-size:14px;">暂无数据</div>
        <!-- 表格展示 -->
        <el-table :data="tableData" border stripe
          :header-cell-style="{ background: '#E8F0FA', color: '#2A303B', fontWeight: '500' }" class="custom-table"
          tooltip-effect="dark" style="width: 100%">
          <el-table-column prop="name" label="全体/班级" align="center">
            <!-- <template  slot-scope="scope">
                {{scope.row.type==0?'全体':'班级'}}
            </template> -->
          </el-table-column>
          <!-- 动态生成列：遍历 distributions -->
          <el-table-column v-for="(scored, index) in tableData[0].distributions" :key="index"
            :label="`${scored.rangeStart} - ${scored.rangeEnd}`">
            <!-- 固定列：人数 -->
            <el-table-column label="人数" align="center">
              <template #default="{ row }">
                <!-- 计算当前行的总人数 -->
                {{ row.distributions[index].currentCount }}
              </template>
            </el-table-column>

            <!-- 固定列：累计 -->
            <el-table-column label="累计" align="center">
              <template #default="{ row }">
                <!-- 计算当前行的累计总数 -->
                {{ row.distributions[index].accumulatedCount }}
              </template>
            </el-table-column>
          </el-table-column>
          <!-- <el-table-column prop="className" label="班级" align="center" /> -->
          <!-- <el-table-column
						v-for="(question, index) in studentlist[0].smallQuestions || []"
						:key="question.questionNumber"
						:label="question.name+question.questionNumber">
                            <template slot-scope="scope">
                                <b style="display:block;width:100%;height:42px;cursor:pointer;line-height:42px;"
                                    @click="handleCellClick(scope.row.smallQuestions[index],scope.row.paperImages)">
                                    {{ scope.row.smallQuestions[index].score }}
                                </b>
                            </template>
                        </el-table-column> -->

          <el-table-column prop="maxScore" label="最高分" align="center">
            <!-- <template slot-scope="scope">
		          {{ formatNumber(scope.row.maxScore) }}
		        </template> -->
          </el-table-column>
          <el-table-column prop="minScore" label="最低分" align="center">
            <!-- <template slot-scope="scope">
		          {{ formatNumber(scope.row.minScore) }}
		        </template> -->
          </el-table-column>
          <el-table-column prop="avgScore" label="平均分" align="center">
            <!-- <template slot-scope="scope">
		          {{ formatNumber(scope.row.avgScore) }}
		        </template> -->
          </el-table-column>
          <el-table-column prop="stdDeviation" label="标准差" align="center">
            <!-- <template slot-scope="scope">
		          {{ formatNumber(scope.row.stdDeviation) }}
		        </template> -->
          </el-table-column>
        </el-table>
      </div>

      <!-- 箱线图部分 -->
      <!-- <div class="box-plot-section">
		    <div class="header-with-select">
		      <h3>2.2.2箱线图</h3>
		    </div>
		    </br>
		    <div class="chart-container">
		      <div ref="boxPlotRef" style="width: 100%; height: 400px"></div>
		    </div>
		  </div> -->

      <!--  2.2.3空白率-->
      <!-- <div class="blank-rate-section">
		    <div class="header-with-select">
		      <h3>2.2.3空白率分布</h3>
		    </div>
		    <el-table 
		      :data="blankRateData" 
		      border 
		      stripe
		      style="width: 100%"
		    >
		      <el-table-column prop="range" label="空白率" align="center" width="120">
		        <template slot-scope="scope">
		          {{ scope.row.start }}%-{{ scope.row.end }}%
		        </template>
		      </el-table-column>
		      <el-table-column prop="students" label="名单" align="center">
		        <template slot-scope="scope">
		          {{ scope.row.students.join('、') || '-' }}
		        </template>
		      </el-table-column>
		    </el-table>
		  </div> -->

      <!--  2.2.4两分五率-->
      <div class="score-rate-section anchor-offset" id="Two-point-five-rate">
        <h3 class="header-with-select">两分五率</h3>
        <div class="statistics-table">
          <el-table :data="scoreRateData" border stripe
            :header-cell-style="{ background: '#E8F0FA', color: '#2A303B', fontWeight: '500' }" class="custom-table"
            tooltip-effect="dark" style="width: 100%">
            <el-table-column label="全体/班级" align="center">
              <template slot-scope="scope">
                {{ scope.row.type == 0 ? '全体' : '班级' }}
              </template>
            </el-table-column>
            <el-table-column prop="submitCount" label="提交人数" align="center" />
            <el-table-column prop="highestScore" label="最高分" align="center" />
            <el-table-column prop="lowestScore" label="最低分" align="center" />
            <el-table-column label="平均分" align="center">
              <el-table-column prop="objectiveAvg" label="客观题" align="center" />
              <el-table-column prop="subjectiveAvg" label="主观题" align="center" />
              <el-table-column prop="totalAvg" label="全体" align="center" />
            </el-table-column>
            <el-table-column label="标准差" align="center">
              <el-table-column prop="objectiveStd" label="客观题" align="center" />
              <el-table-column prop="subjectiveStd" label="主观题" align="center" />
              <el-table-column prop="totalStd" label="全体" align="center" />
            </el-table-column>
            <el-table-column label="满分" align="center">
              <el-table-column prop="fullScoreCount" label="人数" align="center" />
              <el-table-column prop="fullScoreRate" label="占比" align="center" />
            </el-table-column>
            <el-table-column label="优秀" align="center">
              <el-table-column prop="excellentCount" label="人数" align="center" />
              <el-table-column prop="excellentRate" label="占比" align="center" />
            </el-table-column>
            <el-table-column label="良好" align="center">
              <el-table-column prop="goodCount" label="人数" align="center" />
              <el-table-column prop="goodRate" label="占比" align="center" />
            </el-table-column>
            <el-table-column label="及格" align="center">
              <el-table-column prop="passCount" label="人数" align="center" />
              <el-table-column prop="passRate" label="占比" align="center" />
            </el-table-column>
            <el-table-column label="低分" align="center">
              <el-table-column prop="lowCount" label="人数" align="center" />
              <el-table-column prop="lowRate" label="占比" align="center" />
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 2.2.5 学优生/学困生分布 -->
      <div class="student-distribution-section anchor-offset" id="student-distribution">
        <h3 class="header-with-select">学优生/学困生分布</h3>
        <div class="statistics-table">
          <el-table :data="studentDistributionData" border stripe
            :header-cell-style="{ background: '#E8F0FA', color: '#2A303B', fontWeight: '500' }" class="custom-table"
            tooltip-effect="dark" style="width: 100%">
            <el-table-column prop="name" label="全体/班级" align="center">
              <!-- <template  slot-scope="scope">
                {{scope.row.type==0?'全体':'班级'}}
              </template> -->
            </el-table-column>
            <!-- <el-table-column prop="className" label="班级" align="center" /> -->
            <el-table-column label="学优生" align="center">
              <el-table-column prop="excellentCount" label="人数" align="center" />
              <el-table-column prop="excellentRate" label="占比" align="center" />
              <el-table-column prop="excellentAvg" label="均分" align="center" />
            </el-table-column>
            <el-table-column label="学困生" align="center">
              <el-table-column prop="poorCount" label="人数" align="center" />
              <el-table-column prop="poorRate" label="占比" align="center" />
              <el-table-column prop="poorAvg" label="均分" align="center" />
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!-- 2.2.6 学优生/学困生名单 -->
      <div class="student-distribution-section anchor-offset" id="student-distributionname">
        <h3 class="header-with-select">学优生名单</h3>
        <div class="statistics-table">
          <el-table :data="sutdentDistributionDataname" border stripe
            :header-cell-style="{ background: '#E8F0FA', color: '#2A303B', fontWeight: '500' }" class="custom-table"
            tooltip-effect="dark" style="width: 100%">
            <el-table-column label="" align="center">
              <template slot-scope="scope">
                {{ scope.row.name }}班
              </template>
            </el-table-column>
            <el-table-column label="学优生名单">
              <template slot-scope="scope">
                <span v-if="scope.row.excellentList && scope.row.excellentList.length == 0">-</span>
                <Expandable :text="scope.row.excellentList.map(item => item.studentName).join('、')" v-else>
                </Expandable>
                <!-- <span v-else v-for="(item, chilindex) in scope.row.excellentList" :key="`excellent-${chilindex}`">{{
                  item.studentName }}{{ scope.row.excellentList.length - 1 == chilindex ? '' : '、' }}</span> -->
              </template>
            </el-table-column>
            <el-table-column label="学困生名单">
              <template slot-scope="scope">
                <span v-if="scope.row.poorList && scope.row.poorList.length == 0">-</span>
                <Expandable :text="scope.row.poorList.map(item => item.studentName).join('、')" v-else>
                </Expandable>
                <!-- <span v-for="(item, chilindex) in scope.row.poorList" v-else :key="`poor-${chilindex}`">{{
                  item.studentName }}{{ scope.row.poorList.length - 1 == chilindex ? '' : '、' }}</span> -->
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getScoreDistribution, getBoxPlotData, getBlankRate, getScoreRates, getStudentDistribution } from '@/api/score'
import * as echarts from 'echarts'
import Expandable from '@/components/expandable.vue';
export default {
  name: 'ScoreDistribution',
  props: {
    examId: {
      type: [String, Number],
      required: true
    },
    classId: {
      type: [String, Number],
      required: true
    },
    gradeId: {
      type: [String, Number],
      required: true
    },
    subjectId: {
      type: [String, Number],
      required: true
    }
  },
  data () {
    return {
      segment: 5,
      chartInstance: null,
      boxPlotChart: null,
      tableData: [{ distributions: [] }],
      boxPlotData: null,
      blankRateData: [],
      scoreRateData: [],
      studentDistributionData: [],
      loading: false,
      hasLoaded: false,
      loadingPromise: null,
      sutdentDistributionDataname: []
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy () {
    // 清理图表实例和事件监听
    if (this.boxPlotChart) {
      window.removeEventListener('resize', this.boxPlotChart.resize)
      this.boxPlotChart.dispose()
      this.boxPlotChart = null
    }
  },
  methods: {
    async loadData () {
      // 防止重复加载
      if (this.loadingPromise) {
        return this.loadingPromise;
      }

      // 如果已经加载过且有数据，则不重复加载
      if (this.hasLoaded && this.studentDistributionData.length > 0) {
        return;
      }

      try {
        this.loading = true;

        // 保存 Promise 引用
        this.loadingPromise = Promise.all([
          getScoreDistribution(this.examId, this.classId, this.segment),
          getScoreRates(this.examId, this.classId, this.gradeId, this.subjectId),
          getStudentDistribution(this.examId, this.classId)
        ]);

        const [distRes, scoreRateRes, studentDistRes] = await this.loadingPromise;

        if (distRes && distRes.code === 200) {
          this.tableData = distRes.data
          console.info('tableData', this.tableData)
          let echartlist = distRes.data.filter(item => item.type == 1);
          this.updateChart(echartlist[0].distributions);
        }

        if (scoreRateRes && scoreRateRes.code === 200) {
          this.scoreRateData = scoreRateRes.data;
        }

        if (studentDistRes && studentDistRes.code === 200) {
          this.studentDistributionData = studentDistRes.data;
          this.sutdentDistributionDataname = studentDistRes.data.filter(item => item.type == 1);
        }

        this.hasLoaded = true;

      } catch (error) {
        console.error('加载数据失败:', error);
        this.$message.error('加载成绩分布数据失败');
      } finally {
        this.loading = false;
        this.loadingPromise = null;
      }
    },

    initChart () {
      this.chartInstance = echarts.init(this.$refs.chartRef)
    },

    updateChart (data) {
      console.info('datalistlist', data)
      const option = {
        title: {
          text: '人数',
          left: 'center',
          top: 10
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: '{b}: {c}人'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: data.map(item => `${item.rangeStart}-${item.rangeEnd}分`),
          axisLabel: {
            interval: 0,
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '',
          minInterval: 1,
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: [{
          name: '',
          type: 'bar',
          data: data.map(item => item.currentCount),
          barWidth: '60%',
          label: {
            show: true, // 显示标签
            position: 'top', // 标签位置在柱子顶部
            formatter: '{c}人' // 标签内容格式化
          },
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#295CFF' },
              { offset: 0.5, color: '#295CFF' },
              { offset: 1, color: '#295CFF' }
            ])
          },
          emphasis: {
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#295CFF' },
                { offset: 0.7, color: '#295CFF' },
                { offset: 1, color: '#295CFF' }
              ])
            }
          }
        }]
      }
      this.chartInstance.setOption(option)
    },

    initBoxPlot () {
      const chartDom = document.getElementById('boxPlot')
      if (!chartDom) {
        console.warn('图表容器元素不存在')
        return
      }

      this.boxPlotChart = echarts.init(chartDom)

      window.addEventListener('resize', () => {
        this.boxPlotChart && this.boxPlotChart.resize()
      })
    },

    updateBoxPlot (data) {
      if (!this.boxPlotChart) {
        console.warn('图表实例不存在，无法更新数据')
        return
      }

      const option = {
        title: {
          text: '成绩分布箱线图',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            return `
              95%分位: ${params.data[5]}<br/>
              75%分位: ${params.data[4]}<br/>
              中位数: ${params.data[3]}<br/>
              25%分位: ${params.data[2]}<br/>
              5%分位: ${params.data[1]}<br/>
            `
          }
        },
        grid: {
          left: '10%',
          right: '10%',
          bottom: '15%'
        },
        xAxis: {
          type: 'category',
          data: ['班级成绩分布'],
          boundaryGap: true,
          nameGap: 30,
          splitArea: {
            show: false
          },
          axisLabel: {
            show: true
          },
          splitLine: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          name: '分数',
          min: 0,
          max: 100,
          splitArea: {
            show: true
          }
        },
        series: [{
          name: '箱线图',
          type: 'boxplot',
          data: [data],
          itemStyle: {
            color: '#409EFF',
            borderColor: '#409EFF'
          },
          emphasis: {
            itemStyle: {
              borderColor: '#409EFF',
              shadowBlur: 10,
              shadowColor: 'rgba(0,0,0,0.3)'
            }
          }
        }]
      }
      this.boxPlotChart.setOption(option)
    },

    handleSegmentChange () {
      // 分段改变时需要重新加载
      this.hasLoaded = false;
      this.loadData();
    },

    handleResize () {
      this.chartInstance?.resize()
      this.boxPlotChart?.resize()
    },

    formatNumber (value) {
      return Number(value).toFixed(2)
    }
  },
  watch: {
    // 优化 watch 逻辑
    examId (newVal) {
      if (newVal && this.classId && !this.hasLoaded) {
        this.loadData();
      }
    },
    classId (newVal) {
      if (newVal && this.examId && !this.hasLoaded) {
        this.loadData();
      }
    }
  },
  components: {
    Expandable
  }
}
</script>

<style scoped>
.score-distribution {
  background: #FFFFFF;
  box-shadow: 0 4px 16px 0 #5572921a;
  border-radius: 10px;
  padding: 24px;

}

.distribution-section,
.box-plot-section {
  margin-bottom: 20px;
}

.box-plot-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 4px;
}

.header-with-select {
  font-size: 16px;
  color: #2A303B;
  margin-bottom: 14px;
}

.segment-control {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 615px;
  height: 42px;
  background: rgba(41, 92, 255, 0.04);
  border: 1px solid rgba(41, 92, 255, 0.2);
  border-radius: 4px;
  margin: 0 auto;
  font-size: 14px;
}

.buttoncontent {
  box-sizing: border-box;
  width: 100px;
  height: 22px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  background: #fff;
  padding: 0 8px;
  color: #5B6371
}

.buttoncontent i {
  font-style: normal;
  color: #B3B8C2;
  font-size: 12px;
  line-height: 22px;
}

.buttoncontent>>>.el-input {
  width: 50px;
  height: 22px;
  border: none;
  background: none;
  text-align: center;
}

.buttoncontent>>>.el-input__inner {
  border: none;
  background: none;
  height: 22px;
  margin: 0;
  padding: 0;
  font-weight: bold;
}

.segment-control>>>.el-button {
  width: 58px;
  height: 22px;
  background: #295CFF;
  border-radius: 11px;
  color: #fff;
  border: none;
  line-height: 22px;
  padding: 0;
  margin-left: 35px;
}

.label {
  color: #606266;
  font-size: 14px;
}

.chart-container {
  margin: 20px 0;
  padding: 20px;
  border-radius: 4px;
}

.highlight-count {
  color: #409EFF;
  font-weight: bold;
}

.blank-rate-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.score-rate-section {
  background: #fff;
  border-radius: 4px;
}

.student-list {
  margin-top: 5px;
  font-size: 12px;
  color: #606266;
}

.student-distribution-section {
  background: #fff;
  border-radius: 4px;
  margin-bottom: 20px;
  margin-top: 24px;
}

.scoreStateTitle {
  font-size: 18px;
  color: #295CFF;
  line-height: 45px;
  font-weight: normal;
  position: relative;
  padding-left: 25px;
  font-weight: bold;
}

.scoreStateTitle:after {
  content: '';
  width: 14px;
  height: 14px;
  opacity: 0.5;
  background: #295CFF;
  border-radius: 14px;
  position: absolute;
  left: 0;
  top: 15px;
}

.scoreStateTitle::before {
  content: '';
  width: 8px;
  height: 8px;
  opacity: 0.2;
  background: #295CFF;
  border-radius: 14px;
  position: absolute;
  left: 10px;
  top: 23px;
}

.custom-table {
  width: 100%;
  border: 1px solid rgba(216, 228, 240, 1);
  border-radius: 10px;
  border-right: none;
  border-bottom: none;
  margin-top: 0;
}

/* 自定义表格内部元素的样式 */
.custom-table>>>.el-table__header-wrapper th {
  background-color: rgb(232, 240, 250);
  height: 42px;
  padding: 0;
  text-align: center;
  font-weight: normal
}

.custom-table>>>.el-table__row td {
  height: 42px;
  padding: 0;
  text-align: center;
  border-bottom: none;
  border-right: solid 1px rgba(216, 228, 240, 1);
}

.el-table .warning-row {
  background: #ffffff;
}

.el-table .success-row {
  background: #D8E4F0;
}
.anchor-offset {
  scroll-margin-top: 60px;
}
</style>